package com.linghui.videoplus.ipai.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import com.google.gson.Gson;
import com.linghui.videoplus.ipai.R;
import com.linghui.videoplus.ipai.VideoPlusApplication;
import com.linghui.videoplus.ipai.activity.MessageBoxActivity;
import com.linghui.videoplus.ipai.api.db.VideoPlusDB;
import com.linghui.videoplus.ipai.bean.MessageBean;
import com.linghui.videoplus.ipai.utils.LogUtils;

public class MessageService extends Service {
	private static final String LOGTAG = LogUtils.makeLogTag(MessageService.class);
	//获取消息线程
    private MessageThread messageThread = null;
    private NotificationManager messageNotificatioManager = null;
    //通知栏消息
    private int messageNotificationID = 1000;
	//设备相关信息
    public String[][] msgHeader=new String[3][2];
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        messageThread = new MessageThread();
        messageThread.start();
        messageNotificatioManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        return super.onStartCommand(intent, flags, startId); 
    }
     
    /**
     * 从服务器端获取消息
     *
     */
    class MessageThread extends Thread{
        public void run() {
//            while(true){
                try {
                	Thread.sleep(1000000);
                	if(VideoPlusApplication.checkNetWorkStatus(MessageService.this)){
                		
                		List<MessageBean> lsit=getServerMessage();
                		
                		for (MessageBean messageBean : lsit) {
                			productNotification(messageBean);
						}
                   	}
                } catch (Exception e) {
                    e.printStackTrace();
                }
//            }
        }
    }
 
   /**
    * 产生通知
    * @param msg
    */
    public void productNotification(MessageBean messageBean){
        Intent messageIntent =  new Intent(MessageService.this, MessageBoxActivity.class);
        messageIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);   
       
        PendingIntent messagePendingIntent = PendingIntent.getActivity(MessageService.this,messageNotificationID,
        								messageIntent,PendingIntent.FLAG_UPDATE_CURRENT);
     
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.adapter_notification);  
        contentView.setImageViewResource(R.id.image,R.drawable.icon);  
        contentView.setTextViewText(R.id.title,"看看推荐");  
        contentView.setTextViewText(R.id.msg, messageBean.getTitle());  
        contentView.setTextViewText(R.id.time,messageBean.getCreateDateStr()); 
        
        Notification messageNotification =  new Notification();
        messageNotification.icon = R.drawable.icon;
        messageNotification.tickerText = "看看推荐";
        messageNotification.defaults = Notification.DEFAULT_SOUND;
        messageNotification.flags = Notification.FLAG_AUTO_CANCEL; 
        messageNotification.when=System.currentTimeMillis();
        messageNotification.contentView = contentView;  
        messageNotification.contentIntent = messagePendingIntent; 
        messageNotificatioManager.notify(messageNotificationID, messageNotification);
        messageNotificationID++;
        
        VideoPlusDB vDB=new VideoPlusDB(MessageService.this);
        vDB.insertMessage(messageBean);
        vDB.closeDb();
    }
    
    
    /**
     * @return 返回服务器要推送的消息，否则如果为空的话，不推送
     */
    public List<MessageBean> getServerMessage(){	
    	List<MessageBean> msgList=new ArrayList<MessageBean>();
    	try {
//			String response=new SmgnewsGet2ApiImpl().doGet(pushUrl, msgHeader);
			String response="[{\"id\":\"1\",\"title\":\"新消息1\",\"describ\":\"描述1\",\"createDateStr\":\"2012-06-10 8:03\"}" +
					",{\"id\":\"2\",\"title\":\"新消息2\",\"describ\":\"描述3\",\"createDateStr\":\"2012-06-10 8:03\"}]";
			
			Log.i(LOGTAG, response);
			if(response!=null&&!response.equals("")){
				Gson gson = new Gson();
				java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Map<String,String>>>() {}.getType();
				List<Map<String, String>> list = gson.fromJson(response, type);
				for (int i = 0; i < list.size(); i++) {
					Map<String, String> map=list.get(i);
					MessageBean bean= new MessageBean();
					bean.setId((String)map.get("id"));
					bean.setTitle((String)map.get("title"));
					bean.setDescribe((String)map.get("describ"));
					bean.setCreateDateStr((String)map.get("createDateStr"));
					bean.setIsRead(MessageBean.UNREAD);
					bean.setIsReplay(MessageBean.UNREPLAY);
					msgList.add(bean);
				}
			}
    	} catch(Exception ex){
			Log.e(LOGTAG, "response is error!");
		}
        return msgList;
    }

	@Override
	public void onDestroy() {
		System.exit(0);
		super.onDestroy();
	}
}
